//
//  KLMVerticalSliderView.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/7.
//

import UIKit

private let thumbW = 30.0
private let thumbH = 3.0

private let iconWH = 24.0

class KLMVerticalSliderView: UIView {
    
    // MARK: - 配置接口
    typealias ValueChangedBlock = (_ value: CGFloat, _ control: KLMVerticalSliderView) -> Void
    var valueChanged: ValueChangedBlock?
    var valueEndChanged: ValueChangedBlock?
    
    // MARK: - 配置属性
    var minValue: CGFloat = 0.0 {
        didSet { updateDisplay() }
    }
    
    var maxValue: CGFloat = 100.0 {
        didSet { updateDisplay() }
    }
    
    var step: CGFloat = 1.0
    
    var value: CGFloat = 50.0 {
        didSet {
            value = clampedValue().roundedTo(step: step)
            updateDisplay()
            valueChanged?(value, self)
        }
    }
    
    var unit: String = "%" {
        didSet {
            updateDisplay()
        }
    }
    
    var iconName: String = "light" {
        didSet { iconImageView.image = UIImage(named: iconName) }
    }
    
    // MARK: - UI元素
    private let trackView = UIView()
    private let gradientLayer = CAGradientLayer()
    private let thumbView = UIView()
    private let iconImageView = UIImageView()
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    convenience init(
        frame: CGRect = .zero,
        value: CGFloat = 50.0,
        unit: String = "%",
        iconName: String = "",
        minValue: CGFloat = 0.0,
        maxValue: CGFloat = 100.0,
        step: CGFloat = 1.0
    ) {
        self.init(frame: frame)
        self.minValue = minValue
        self.maxValue = maxValue
        self.step = step
        self.value = value
        self.unit = unit
        self.iconName = iconName
        configure(value: value, unit: unit, iconName: iconName)
    }
    // MARK: - 公共方法
    func configure(
        value: CGFloat? = nil,
        unit: String? = nil,
        iconName: String? = nil,
        minValue: CGFloat? = nil,
        maxValue: CGFloat? = nil,
        step: CGFloat? = nil
    ) {
        if let unit = unit { self.unit = unit }
        if let iconName = iconName { self.iconName = iconName }
        if let minValue = minValue { self.minValue = minValue }
        if let maxValue = maxValue { self.maxValue = maxValue }
        if let step = step { self.step = step }
        if let value = value {
            self.value = value
            valueChanged?(value, self)
        }
        updateDisplay()
    }
    private func commonInit() {
        setupUI()
        setupGesture()
        updateDisplay()
    }
    // MARK: - UI配置
    private func setupUI() {
        // 轨道背景
        trackView.backgroundColor = rgba(242, 242, 242, 1)
        trackView.layer.cornerRadius = 16
        trackView.clipsToBounds = true
        addSubview(trackView)
        
        // 渐变层
        gradientLayer.colors = [
            rgba(250, 137, 2, 1).cgColor,
            rgba(255, 248, 239, 1).cgColor
        ]
        trackView.layer.addSublayer(gradientLayer)
        
        // 滑块指示器
        thumbView.backgroundColor = .white
        addSubview(thumbView)
        
        // 底部图标
        iconImageView.contentMode = .scaleAspectFit
        addSubview(iconImageView)
    }
    // 颜色配置
    func setGradientColors(start: UIColor, end: UIColor) {
        gradientLayer.colors = [start.cgColor, end.cgColor]
    }
    // MARK: - 布局
    override func layoutSubviews() {
        super.layoutSubviews()
        trackView.frame = bounds
        // 渐变层布局
        let valueRatio = (value - minValue) / (maxValue - minValue)
        let gradientHeight = bounds.height * valueRatio
        gradientLayer.frame = CGRect(
            x: 0,
            y: bounds.height - gradientHeight,
            width: bounds.width,
            height: gradientHeight
        )
        var thumbY = bounds.height - gradientHeight + 5
        if valueRatio == 0 {
            thumbY = bounds.height - thumbH
        }
        thumbView.frame = CGRect(x: (bounds.width - thumbW)*0.5, y: thumbY, width: thumbW, height: thumbH)
        // 图标布局
        iconImageView.frame = CGRect(x: (bounds.width - iconWH)*0.5,
                                   y: bounds.height-40,
                                     width: iconWH,
                                     height: iconWH)
    }
    // MARK: - 手势处理
    private func setupGesture() {
        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        addGestureRecognizer(pan)
    }
    private var initialTouchY: CGFloat = 0
    
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        let location = gesture.location(in: self)
        let trackFrame = trackView.frame
        
        switch gesture.state {
        case .began:
            initialTouchY = location.y
        case .changed, .ended:
            let availableHeight = trackFrame.height
            let touchY = (location.y - trackFrame.minY).customClamped(to: 0.0...availableHeight)
            let ratio = 1 - (touchY / availableHeight)
            
            // 计算原始值
            let rawValue = minValue + ratio * (maxValue - minValue)
            
            // 应用步进值
            let steppedValue = (rawValue / step).rounded() * step
            
            // 更新数值
            value = steppedValue.customClamped(to: minValue...maxValue)
            
        default: break
        }
    }
    
    // MARK: - 数值处理
    private func clampedValue() -> CGFloat {
        return min(max(value, minValue), maxValue)
    }
    
    private func updateDisplay() {
        setNeedsLayout()
        
        // 渐变动画
        UIView.animate(withDuration: 0.2) {
            self.gradientLayer.opacity = self.value > self.minValue ? 1.0 : 0.8
        }
    }
}

// MARK: - 扩展工具
extension CGFloat {
    func roundedTo(step: CGFloat) -> CGFloat {
        guard step > 0 else { return self }
        return (self / step).rounded() * step
    }
    
    func customClamped(to range: ClosedRange<CGFloat>) -> CGFloat {
        let validLower = Swift.min(range.lowerBound, range.upperBound)
        let validUpper = Swift.max(range.lowerBound, range.upperBound)
        return Swift.max(validLower, Swift.min(self, validUpper))
    }
}

//private let SliderInitValue = 0.3
//
//class KLMVerticalSliderView: UIView {
//
//    // MARK: - 配置接口
//    typealias ValueChangedBlock = (_ value: CGFloat, _ control: KLMVerticalSliderView) -> Void
//    // 值变化回调（携带自身实例）
//    var valueChanged: ValueChangedBlock?
//    var valueEndChanged: ValueChangedBlock?
//    
//    // MARK: - 原有实现
//    var value: CGFloat = SliderInitValue {
//        didSet {
//            updateDisplay()
//            valueChanged?(value, self)  // 携带自身实例方便识别
//        }
//    }
//    var type: String = "" {
//        didSet { updateDisplay() }
//    }
//    var unit: String = "%" {
//        didSet { updateDisplay() }
//    }
//    var iconName: String = "" {
//        didSet { iconImageView.image = UIImage(named: iconName) }
//    }
//    
//    // 代码初始化（基础方法）
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        commonInit()
//    }
//    
//    // xib/storyboard初始化（基础方法）
//    required init?(coder: NSCoder) {
//        super.init(coder: coder)
//        commonInit()
//    }
//    
//    // 便利初始化方法（代码创建时快速配置）
//    convenience init(
//        frame: CGRect = .zero,
//        type: String = "",
//        value: CGFloat = SliderInitValue,
//        unit: String = "%",
//        iconName: String = ""
//    ) {
//        self.init(frame: frame)
//        self.type = type
//        self.value = value
//        self.unit = unit
//        self.iconName = iconName
//        configure(type: type, value: value, unit: unit, iconName: iconName)
//    }
//    
//    // 公共初始化配置
//    private func commonInit() {
//        setupUI()
//        setupGesture()
//        updateDisplay()
//    }
//    // 确保xib中的修改生效
//    override func awakeFromNib() {
//        super.awakeFromNib()
//        updateDisplay()
//        setNeedsLayout()
//    }
//    // UI元素
//    let gradientLayer = CAGradientLayer()
//    let titleLabel = UILabel()
//    let iconImageView = UIImageView()
//    let indictorView = UIView()
//    
//    // 手势识别
//    private var initialTouchY: CGFloat = 0
//    private var initialValue: CGFloat = 0
//    
//    // 公共配置方法
//    func configure(type: String? = nil,
//                   value: CGFloat = SliderInitValue,
//                   unit: String? = nil,
//                   iconName: String? = nil) {
//        if let type = type { self.type = type }
//        if let unit = unit { self.unit = unit }
//        if let iconName = iconName { self.iconName = iconName }
//        if value != SliderInitValue {
//            self.value = value
//            self.valueChanged?(value, self)
//        }
//        updateDisplay()
//        setNeedsLayout()
//    }
//    
//    // 颜色配置
//    func setGradientColors(start: UIColor, end: UIColor) {
//        gradientLayer.colors = [start.cgColor, end.cgColor]
//    }
//    
//    private func setupUI() {
//        backgroundColor = rgba(242, 242, 242, 1)
//        layer.cornerRadius = 16
//        clipsToBounds = true
//        
//        // 渐变层配置
//        gradientLayer.cornerRadius = 0
//        gradientLayer.colors = [
//            rgba(250, 137, 2, 1).cgColor,
//            rgba(255, 248, 239, 1).cgColor
//        ]
//        gradientLayer.locations = [0, 1]
//        layer.addSublayer(gradientLayer)
//        
//        // 图标
//        iconImageView.image = UIImage(named: "light")
//        iconImageView.contentMode = .scaleAspectFill
//        addSubview(iconImageView)
//        
//        indictorView.backgroundColor = .white
//        addSubview(indictorView)
//    }
//    
//    private func setupGesture() {
//        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
//        self.addGestureRecognizer(panGesture)
//    }
//    
//    override func layoutSubviews() {
//        super.layoutSubviews()
//        
//        // 渐变层布局
//        let gradientHeight = bounds.height * value
//        gradientLayer.frame = CGRect(
//            x: 0,
//            y: bounds.height - gradientHeight,
//            width: bounds.width,
//            height: gradientHeight
//        )
//        indictorView.frame = CGRect(x: (bounds.width - 18)*0.5, y: bounds.height - gradientHeight + 6, width: 18, height: 2)
//        
//        // 标签布局
//        titleLabel.frame = CGRect(x: 0, y: 36, width: bounds.width, height: 16)
//        iconImageView.frame = CGRect(x: bounds.width/2-12, y: bounds.height-40, width: 24, height: 24)
//    }
//    
//    private func updateDisplay() {
//        setNeedsLayout()
//        // 渐变动画
//        UIView.animate(withDuration: 0.2) {
//            self.gradientLayer.opacity = self.value > 0.1 ? 1.0 : 0.8
//        }
//    }
//    
//    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
//        
//        switch gesture.state {
//        case .began:
//            initialTouchY = gesture.location(in: self).y
//            initialValue = value
//        case .changed:
//            let delta = (initialTouchY - gesture.location(in: self).y) / bounds.height
//            value = max(0, min(1, initialValue + delta))
//        case .ended:
//            let delta = (initialTouchY - gesture.location(in: self).y) / bounds.height
//            let endValue = max(0, min(1, initialValue + delta))
//            valueEndChanged?(endValue, self)
//        default:
//            break
//        }
//    }
//
//}
